package cn.virens.web.components.shiro.spring;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * Shiro 使用 Spring 缓存管理器
 * @作者 :loioi
 * @创建时间 :2017年7月17日
 */
public class SpringCacheManage implements CacheManager, ApplicationContextAware {
	private ApplicationContext applicationContext;
	private org.springframework.cache.CacheManager cacheManager;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	/**
	 * 注入Spring的缓存管理器
	 * @param cacheManager
	 */
	public SpringCacheManage(org.springframework.cache.CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}

	/**
	 * 获取 缓存
	 */
	@Override
	public <K, V> Cache<K, V> getCache(String name) throws CacheException {
		try {
			return new SpringCache<K, V>(getCacheManager().getCache(name));
		} catch (Throwable t) {
			throw new CacheException(t);
		}
	}

	/**
	 * 获取Spring 缓存管理器，如果为空则直接从Bean里面取
	 * @return
	 */
	protected org.springframework.cache.CacheManager getCacheManager() {
		if (cacheManager == null) {
			this.cacheManager = applicationContext.getBean(org.springframework.cache.CacheManager.class);
		}

		return cacheManager;
	}
}
